package com.cxm.top_forum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cxm.top_forum.mapper.ArticleMapper;
import com.cxm.top_forum.mapper.LikesMapper;
import com.cxm.top_forum.pojo.Article;
import com.cxm.top_forum.pojo.Likes;
import com.cxm.top_forum.pojo.req.ArticleReq;
import com.cxm.top_forum.pojo.vo.ArticleItemVo;
import com.cxm.top_forum.pojo.vo.ArticlePage;
import com.cxm.top_forum.pojo.vo.ArticleVo;
import com.cxm.top_forum.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author cxm
 * @date 2021/8/6
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private LikesMapper likesMapper;

    @Override
    public ArticleVo listArticle(Page<ArticlePage> page, ArticleReq req) {
        IPage<ArticlePage> article = articleMapper.listArticle(page, req);
        ArticleVo articleVo = new ArticleVo();
        articleVo.setList(article.getRecords());
        articleVo.setTotal(article.getTotal());
        articleVo.setPageNum(article.getCurrent());
        return articleVo;
    }

    @Override
    public ArticleItemVo getWithTagById(Long id) {
        return articleMapper.getWithTagById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void like(Likes likes) {
        Article article = articleMapper.selectById(likes.getParentId());
        article.setLikes(article.getLikes()+1);
        articleMapper.updateById(article);
        likesMapper.insert(likes);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void disLike(Likes likes) {
        Article article = articleMapper.selectById(likes.getParentId());
        article.setLikes(article.getLikes()-1);
        articleMapper.updateById(article);
        likesMapper.delete(new QueryWrapper<Likes>().eq("user_id",likes.getUserId()).eq("parent_id",likes.getParentId()));
    }
}
